﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;


namespace YTSK.Common
{
    public class HandleReport
    {
        #region 初始化
        #region 初始化控件
        public static void InitControl(Control main, DataGridView dg, string reportcode)
        {
            ServerConfig.ReLogin();
            var url = string.Format("{0}/api/oms/Report/ReportFilter?ReportCode={2}&token={1}",
                ServerConfig.ServerAddress, ServerConfig.GetToken(), reportcode);
            var ss = Common.handleHttp.Get(url);
            var result = Common.handleJSON.DeserializeResult(ss);
            var l_serach = result.GetListDic("SearchParams");
            var alldeafultval = l_serach.Where(s => s["FieldDefaultValue"].ObjToString().Length > 0
            || s["ControlType"].ObjToString() == "select").ToList();
            for (int k = 0; k < alldeafultval.Count(); k++)
            {
                var scontrol = alldeafultval[k];
                var cc = main.Controls.Find(scontrol["FieldCode"].ObjToString(), true);
                if (cc.Count() > 0)
                {
                    var tmp = cc[0];
                    if (scontrol["FieldDefaultValue"].ObjToString().Length > 0)
                    {
                        if (tmp.GetType() == typeof(DateTimePicker))
                        { ((DateTimePicker)tmp).Value = scontrol["FieldDefaultValue"].ObjToDate(); }
                        if (tmp.GetType() == typeof(TextBox))
                        { ((TextBox)tmp).Text = scontrol["FieldDefaultValue"].ObjToString(); }
                    }
                    if (tmp.GetType() == typeof(ComboBox))
                    {
                        InitControl_Combol(scontrol, (ComboBox)tmp);
                    }

                }

            }

            //var search = l_serach.First(s => s["FieldCode"].ToString() == "dateStart");
            //this.dateStart.Value = search["FieldDefaultValue"].ObjToDate();
            //search = l_serach.First(s => s["FieldCode"].ToString() == "dateEnd");
            //this.dateEnd.Value = search["FieldDefaultValue"].ObjToDate();

            //#region 仓库下拉
            //search = l_serach.First(s => s["FieldCode"].ToString() == "IDWarehouse");
            ////search["FieldDefaultValue"] = cHandleUF.cAccID;
            //InitControl_Combol(search, this.IDWarehouse, false);
            ////if (IDWarehouse.SelectedIndex != 0) { this.IDWarehouse.Enabled = false; }
            //#endregion

            //#region 是否扫描
            //search = l_serach.First(s => s["FieldCode"].ToString() == "bScan");
            //InitControl_Combol(search, this.bScan);
            //#endregion

            //#region 是否下载
            //search = l_serach.First(s => s["FieldCode"].ToString() == "bdownload");
            //InitControl_Combol(search, this.bdownload);
            //#endregion
            var GridColumns = result.GetListDic("GridColumns");
            InitControl_DataGrid(GridColumns, dg);

        }
        #endregion

        #region 设置下拉列表
        private static void InitControl_Combol(Dictionary<string, object> search, ComboBox cb, bool defaultValueFromKey = true)
        {
            var obj = (System.Collections.ArrayList)search["ControlValue"];
            var controlvalue = new List<Dictionary<string, object>>();
            foreach (var item in obj)
            {
                var dic = (Dictionary<string, object>)item;
                controlvalue.Add(dic);
            }
            var id = "";
            var dt = new DataTable();
            dt.Columns.Add("key"); dt.Columns.Add("value");
            for (int i = 0; i < controlvalue.Count; i++)
            {
                var v = controlvalue[i];
                var dtr = dt.NewRow();
                dtr["key"] = v["key"];
                dtr["value"] = v["value"];
                if (defaultValueFromKey)
                {
                    if (v["key"].ToString() == search["FieldDefaultValue"].ToString())
                    { id = v["key"].ToString(); }
                }
                else
                {
                    if (v["value"].ToString().Contains(search["FieldDefaultValue"].ToString()))
                    { id = v["key"].ToString(); }
                }
                dt.Rows.Add(dtr);
            }
            cb.DataSource = dt;
            cb.DisplayMember = "value";
            cb.ValueMember = "key";
            if (id != "")
            { cb.SelectedValue = id; }

        }
        #endregion

        #region 设置DataGrid
        private static void InitControl_DataGrid(List<Dictionary<string, object>> list, DataGridView dg)
        {
            dg.Columns.Clear();
            dg.Columns.Clear();
            dg.Rows.Clear();
            dg.ReadOnly = true;
            dg.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dg.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
            dg.ColumnHeadersHeight = 20;
            for (int i = 0; i < list.Count; i++)
            {
                var dic = list[i];
                if (dic["Code"].ObjToString() == "checkBox")
                { dg.Columns.Add(InitControl_DataGrid_CheckBox()); continue; }
                var dgcolumn = new DataGridViewTextBoxColumn();
                dgcolumn.Name = dic["Code"].ObjToString();
                dgcolumn.DataPropertyName = dic["Code"].ObjToString();
                dgcolumn.HeaderText = dic["Title"].ObjToString();
                dgcolumn.Width = dic["Width"].ObjToInt();
                switch (dic["Align"].ObjToString())
                {
                    case "center":
                        dgcolumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                        break;
                    case "right":
                        dgcolumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        break;
                    default:
                        dgcolumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
                        break;
                }
                if (dic["Width"].ObjToInt() <= 0)
                {
                    dgcolumn.Visible = false;
                }
                dgcolumn.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dg.Columns.Add(dgcolumn);
            }
        }

        private static DataGridViewColumn InitControl_DataGrid_CheckBox()
        {
            var dgcolumn = new DataGridViewTextBoxColumn();
            dgcolumn.Name = "selcol";
            dgcolumn.HeaderText = "选择";
            dgcolumn.DataPropertyName = "selcol";
            dgcolumn.Width = 60;
            dgcolumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgcolumn.ReadOnly = false;
            dgcolumn.Visible = true;
            dgcolumn.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            return dgcolumn;
        }
        #endregion

        #endregion

        #region 获取数据

        #region 计算查询条件
        /// <summary>
        /// 计算查询条件
        /// </summary>
        private static string GetControlValue(Control main)
        {
            var url = "";
            foreach (Control c in main.Controls)
            {
                if (c.GetType() == typeof(DateTimePicker))
                { url += "&" + c.Name + "=" + ((DateTimePicker)c).Value.ToString("yyyy-MM-dd"); }
                if (c.GetType() == typeof(ComboBox))
                { url += "&" + c.Name + "=" + ((ComboBox)c).SelectedValue.ObjToString(); }
                if (c.GetType() == typeof(TextBox))
                { url += "&" + c.Name + "=" + ((TextBox)c).Text.Trim(); }
            }
            url = url.Trim('&');
            return url;
        }
        #endregion

        #region 加载数据
        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="main"></param>
        /// <param name="dg"></param>
        /// <param name="reportcode"></param>

        public static void GetGridData(Control main, DataGridView dg, string reportcode)
        {
            var f = new FrmTip();
            try
            {
                f.Show();
                f.setValue("正在获取数据，时间比较久，请耐心等候", 50);
                //var url = string.Format("{0}/api/oms/Report/ReportData?ReportCode={3}&token={1}&{2}",
                //        ServerConfig.ServerAddress, ServerConfig.Token, GetControlValue(), _reportcode);
                //var ss = Common.handleHttp.Get(url);
                //var result = Common.handleJSON.DeserializeResult(ss);
                //if (result.result != 1) { ServerConfig.Token = ""; MessageBox.Show("服务器错误:" + result.resultdetail); return; }
                //var data = result.GetListDic("data");
                var where_str = GetControlValue(main);
                var result = GetReportData(reportcode, where_str);
                if (result.result != 1) { return; }
                var data = result.GetListDic("data");
                f.setValue("格式化数据", 80);
                dg.Rows.Clear();
                var rows = result.GetVal("TotalRecords").ObjToInt();
                if (rows > data.Count) { rows = data.Count; }
                if (rows == 0)
                { //MessageBox.Show("没有查询到数据，请更改查询条件"); 
                    return;
                }
                dg.Rows.Add(rows);

                for (int i = 0; i < rows; i++)
                {
                    var dic = data[i];
                    var dgr = dg.Rows[i];

                    for (int j = 0; j < dg.Columns.Count; j++)
                    {
                        var colname = dg.Columns[j].Name;
                        if (dic.Keys.Contains(colname))
                        {
                            dgr.Cells[j].Value = dic[colname];
                        }
                    }
                    dgr.Cells["selcol"].Value = (i + 1).ToString();
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message + ex.StackTrace); }
            finally { f.Close(); }
        }
        #endregion

        #region 从服务器获取报表数据
        /// <summary>
        /// 从服务器获取报表数据
        /// </summary>
        /// <param name="reportcode">报表编号</param>
        /// <param name="otherval">其他条件</param>
        /// <returns></returns>
        private static Model.ResultJson GetReportData(string reportcode, string otherval = "")
        {
            var url = string.Format("{0}/api/oms/Report/ReportData?ReportCode={3}&token={1}&{2}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken(), otherval, reportcode);
            var ss = Common.handleHttp.Get(url);
            var result = Common.handleJSON.DeserializeResult(ss);
            if (result.result != 1) {  MessageBox.Show("服务器错误:" + result.resultdetail); return new Model.ResultJson(); }
            return result;
            //var data = result.GetListDic("data");
            //return data;
        }
        #endregion

        #endregion 



    }
}
